#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<vector<int>> fourSumSelf(vector<int> &nums, int target)
{
    if (nums.size() < 4)
        return {};
    vector<vector<int>> result;
    sort(nums.begin(), nums.end());
    if ((target <= 0 && nums[0] > 0) || (target >= 0 && nums[0] > target))
        return {};
    for (int i = 0; i < nums.size(); i++)
    {
        if (i > 0 && (nums[i] == nums[i - 1]))
            continue;
        for (int j = i + 1; j < nums.size(); j++)
        {
            if (j > i + 1 && (nums[j] == nums[j - 1]))
                continue;
            int left = j + 1, right = nums.size() - 1;
            while (left < right)
            {
                long long sum = (long long)nums[i] + nums[j] + nums[left] + nums[right];
                if (sum == target)
                {
                    result.push_back({nums[i], nums[j], nums[left], nums[right]});
                    while (left < right && nums[left] == nums[left + 1])
                        left++;
                    while (left < right && nums[right] == nums[right - 1])
                        right--;
                    left++;
                    right--;
                }
                else if (sum < target)
                    left++;
                else
                    right--;
            }
        }
    }
    return result;
}
